//
//  QRCodeViewController.swift
//  WeiBoOfSwift
//
//  Created by aven wu on 21/04/2018.
//  Copyright © 2018 GML. All rights reserved.
//

import UIKit
import AVFoundation
import SnapKit

class QRCodeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        setUpNaviBar()
        view.addSubview(sacanView)
//        view.addSubview(scanlineImage)

        
    }
    override func viewWillAppear(_ animated: Bool) {
        
        UIView.setAnimationRepeatCount(MAXFLOAT)
        UIView.animate(withDuration: 5) {
            self.scanlineImage.transform = CGAffineTransform.init(translationX: 0, y: -self.sacanView.bounds.height)
            self.scanlineImage.layoutIfNeeded()
        }
        // 开始扫描
        scanQRcode()
        
    }

    func setUpNaviBar() -> Void {
         navigationItem.leftBarButtonItem  = UIBarButtonItem.creatCustomBarButtonItem(imageName: "", highlightedName: "",title:"关闭", target: self, action: #selector(closeVC))
        navigationItem.rightBarButtonItem  = UIBarButtonItem.creatCustomBarButtonItem(imageName: "", highlightedName: "",title:"名片", target: self, action: #selector(gotoMyQRCodeVC))
    }
    
    @objc func closeVC() -> Void {
        navigationController?.dismiss(animated: true, completion: {
            
        })
    }
    @objc func gotoMyQRCodeVC() -> Void {
        let myVC = MyQRCodeViewController()
//        navigationController?.pushViewController(myVC, animated: true)
        
    }
    // MARK:扫描二维码
    private func scanQRcode(){
        // 判断是否有输入添加到会话中
        if !session.canAddInput(deviceInput!) {
            return
        }
        // 判断是否有输出添加到会话中
        if !session.canAddOutput(deviceOutput)  {
            return
        }
        session.addInput(deviceInput!)
        session.addOutput(deviceOutput)
        
        // 只要系统支持  就支持
        deviceOutput.metadataObjectTypes = deviceOutput.availableMetadataObjectTypes
        
        // 设置代理
        deviceOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        
        // 添加扫描图层
        view.layer.insertSublayer(preViewLayer, at: 0)
        // 添加绘制的边框图层到扫描图层上
        preViewLayer.addSublayer(drawLayer)
        // 开始扫描
        session.startRunning()
    }
   
    
    override func updateViewConstraints() {
        sacanView.snp.makeConstraints { (make) -> Void in
            make.center.equalTo(self.view)
        }
//        scanlineImage.snp.makeConstraints { (make) -> Void in
//            make.center.equalTo(self.sacanView)
//        }
        super.updateViewConstraints()
    }
    
    // MARK:懒加载
    private lazy var sacanView:UIView = {
       let sacanview = UIView()
        sacanview.frame = CGRect(x: 0, y: 0, width: view.bounds.size.width * 0.5, height: view.bounds.size.width * 0.5)
        sacanview.backgroundColor = UIColor.clear
        let borderImage = UIImageView()
        borderImage.bounds = sacanview.bounds
        borderImage.image = UIImage(named: "qrcode_border")
        sacanview.addSubview(borderImage)
        // qrcode_scanline_barcode
        let scanlineImage = UIImageView()
        scanlineImage.bounds = sacanview.bounds

        scanlineImage.image = UIImage(named: "qrcode_scanline_barcode")
      
        UIView.animate(withDuration:3.5, delay: 0, options: UIViewAnimationOptions.repeat, animations: {
             scanlineImage.transform = CGAffineTransform.init(translationX: 0.0, y: -self.view.bounds.size.width * 0.5)
        }, completion: nil)
        sacanview.addSubview(scanlineImage)
        
        return sacanview
    }()
    
    private lazy var scanlineImage: UIImageView = {
        let line = UIImageView()
        line.frame = sacanView.frame
        line.image = UIImage(named: "qrcode_scanline_barcode")
        
        return line
    }()
    // 获取会话
    private lazy var session : AVCaptureSession = {
        let se = AVCaptureSession()
        return se
    }()
    // 输入
    private lazy var deviceInput : AVCaptureDeviceInput? = {
       let device = AVCaptureDevice.default(for: AVMediaType.video)
        do {
            let input = try AVCaptureDeviceInput(device: device!)
            return input
        } catch  {
            print(error)
            return nil
        }
    }()
    // 输出
    private lazy var deviceOutput :AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    // 创建预览图层
    private lazy var preViewLayer:AVCaptureVideoPreviewLayer = {
        let layer = AVCaptureVideoPreviewLayer(session:self.session)
        layer.frame = UIScreen.main.bounds
        return layer
        
    }()
    // 创建用于绘制边缘线的图层
    private lazy var drawLayer:CALayer = {
       let layer = CALayer()
        layer.frame = UIScreen.main.bounds
        return layer
    }()
    
}
extension QRCodeViewController:AVCaptureMetadataOutputObjectsDelegate{
    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        print(metadataObjects.last ?? String())
        
        let metadataObject:AVMetadataMachineReadableCodeObject = metadataObjects.last as! AVMetadataMachineReadableCodeObject
        if (metadataObject.stringValue != nil) {
            session.stopRunning()
        }
        // 获取扫描到的二维码位置
        // 获取到corners数据
        for objc in metadataObjects {
            if objc is AVMetadataMachineReadableCodeObject{
                let codeObjct = preViewLayer.transformedMetadataObject(for: objc)
                // 绘制贝塞尔曲线
//                drawQRCodeBorder(coderObject: codeObjct as! AVMetadataMachineReadableCodeObject)
            }
        }
        let alertController = UIAlertController.init(title: "", message: metadataObject.stringValue, preferredStyle: UIAlertControllerStyle.alert)
        // 设置2个UIAlertAction
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {  (UIAlertAction) -> Void in
            
            self.session.startRunning()
        }
        let okAction = UIAlertAction(title: "好的", style: .default) { (UIAlertAction) -> Void in
            self.session.startRunning()

        }
        // 添加
        alertController.addAction(cancelAction)
        alertController.addAction(okAction)
        // 弹出
        present(alertController, animated: true, completion: nil)
    }
    
    private func drawQRCodeBorder(coderObject:AVMetadataMachineReadableCodeObject){
        if coderObject.corners.isEmpty {
            return
        }
        // 创建图层
        let layer = CAShapeLayer()
        layer.lineWidth = 4
        layer.strokeColor = UIColor.green.cgColor
        // 创建路径
        // 将获取到的corners放置到对应的点上
        let path = UIBezierPath()
        let count = coderObject.corners.count
        
        for i in 0..<count  {
            let pointDic = coderObject.corners[i] as! CFDictionary
            var point = CGPoint(dictionaryRepresentation: pointDic)
            if i == 0
            {
                path.move(to: point!)
            }else
            {
                path.addLine(to: point!)
            }
        }
        
        // 关闭路径
        path.close()
        layer.path = path.cgPath
    //        layer.path = UIBezierPath(rect: CGRect(x: 100, y: 100, width: 200, height: 200)).cgPath
        
        // 将绘制好的路径添加到图层drawLayer上
        drawLayer.addSublayer(layer)
        
        
    }
    
}
